package com.jinlongchen.servlet;

import com.jinlongchen.util.DBUtil;
import com.jinlongchen.model.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.security.MessageDigest;
import java.sql.*;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、读取用户信息
        req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String nickname = req.getParameter("nickname");
        String password = req.getParameter("password");
        //TODO:错误检查和处理

        try {

            //2、在存储中进行数据保存(INSERT)
            User user = save(username, nickname, password);
            //3、完成登录（在Session中保存当前登录用户信息）
            HttpSession session = req.getSession();
            session.setAttribute("currentUser", user);
            //4、引导浏览器回到首页（重定向）
            resp.sendRedirect("/");
        }catch (SQLException exc){
            throw new ServletException(exc);
        }
    }

    private User save(String username,String nickname,String password) throws SQLException{
        //基于安全考虑，我们不保存用户的明文密码，我们利用SHA-512对密码做hash
        password = hash(password);

        try (Connection c = DBUtil.getConnection()){
            String sql = "INSERT INTO user(username,nickname,password) VALUES(?,?,?)";
            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)){
                s.setString(1,username);
                s.setString(2,nickname);
                s.setString(3,password);

                s.executeUpdate();

                try (ResultSet rs = s.getGeneratedKeys()){
                    if(!rs.next()){
                        return null;
                    }

                    User user = new User();
                    user.username = username;
                    user.nickname = nickname;
                    user.uid = rs.getInt(1);
                    return user;
                }
            }
        }
    }

    private String hash(String password){
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");

            byte[] bytes = password.getBytes("UTF-8");
            byte[] digest = messageDigest.digest(bytes);
            StringBuilder sb = new StringBuilder();
            for (byte b : digest){
                sb.append(String.format("%02x",b));
            }
            return sb.toString();

        }catch (Exception exc){
            return password;
        }
    }
}
